import asyncio
import aiomysql


# 连接数据库
async def _connect():
    return await aiomysql.connect(
        host='127.0.0.1',
        port=3306,
        # db='',   # 不用指定数据库
        user='root',
        password='root',
    )


# 创建数据库和表
async def init():
    db = await _connect()
    try:
        async with db.cursor() as cursor:
            await cursor.execute('''
CREATE database tornado_db DEFAULT charset utf8;

use tornado_db;

CREATE TABLE posts (
id INT PRIMARY KEY auto_increment,
title VARCHAR(100) NOT NULL,
content text NOT NULL
)
''')
    finally:
        db.close()


# 删除数据库
async def drop():
    db = await _connect()
    try:
        async with db.cursor() as cursor:
            await cursor.execute('''
DROP database IF EXISTS tornado_db;
''')
    finally:
        db.close()


def main():
    asyncio.run(init())
    # asyncio.run(drop())


if __name__ == '__main__':
    main()
